//
//  FPWebViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPWebViewController.h"
#import "FPWebViewModel.h"
#import "FPRankView.h"
#import "FPWebDownView.h"
#import "FPWebRealationModel.h"
#import "FPRelationView.h"
#import "FPRelationItem.h"
#import "UMSocial.h"
#import "FPSqliteManager.h"
#import "FPCollectionWebModel.h"
@interface FPWebViewController ()<UIWebViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UMSocialUIDelegate,UITextFieldDelegate>
@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)FPRankView *topView;
@property(nonatomic,strong)FPWebDownView *webDownView;
@property(nonatomic,strong)NSMutableArray *realations;
@property(nonatomic,strong)FPRelationView *relationView;
@property(nonatomic,strong)UIButton *favoriteButton;
@property(nonatomic,strong)UIButton *shareButton;
@end

@implementation FPWebViewController
- (NSMutableArray *)realations
{
    if (!_realations) {
        _realations = [NSMutableArray array];
        
    }
    return _realations;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"=====%@",self.introModel.title);
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.backgroundColor = [UIColor purpleColor];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , 20)];
    statusBarView.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:statusBarView];
    [self creatNagationBarButton];
   // self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64 +kImageH(60), kScreenWidth, kScreenHeight)];
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64 +kImageH(60), kScreenWidth, kScreenHeight - 64 - kImageH(100) )];
    [(UIScrollView *)self.webView.subviews[0] setScrollEnabled:YES];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    [self setTopView];
    [self addWEbDownView];
     [self webAnalysisWithString:self.stringURl];
    
}

//自定义navagationBar上的按钮
- (void)creatNagationBarButton
{
    UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(kScreenWidth-kImageW(60), 0, kImageW(70), 30)];
    self.favoriteButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.favoriteButton addTarget:self action:@selector(favoriteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.favoriteButton setImage:[UIImage imageNamed:@"icon_bookmark 2@3x"] forState:UIControlStateNormal];
    self.favoriteButton.frame = CGRectMake(0, 0, kImageW(30), kImageW(30));
    [myView addSubview:_favoriteButton];
    self.shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
     [self.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
     [self.shareButton setImage:[UIImage imageNamed:@"ic_share_blue"] forState:UIControlStateNormal];
    self.shareButton.frame = CGRectMake(kImageW(40), 0, kImageW(30), kImageW(30));
    [myView addSubview:_shareButton];
     UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithCustomView:myView];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
}
- (void)favoriteButtonAction:(UIButton *)sender
{
    if (![FPUserModel ShareInstance].userName) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"请登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    NSArray *webArray = [FPSqliteManager selectWebCollectTitleWithUserName:[FPUserModel ShareInstance].userName];
    if (webArray.count == 0) {
        [FPSqliteManager insertWebTable:self.introModel];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    else
    {
        for (NSString *title in webArray) {
            if ([title isEqualToString:self.introModel.title]) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"亲,你已经收藏过了" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alert show];
                return;
            }
        }
        [FPSqliteManager insertWebTable:self.introModel];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];

    }
    [FPSqliteManager insertWebTable:self.introModel];
    FPCollectionWebModel *colWebModel = [[FPCollectionWebModel alloc]init];
    colWebModel.title = self.introModel.title;
    colWebModel.userName = [FPUserModel ShareInstance].userName;
    [FPSqliteManager insertWebCollectTable:colWebModel];
}
- (void)shareButtonAction:(UIButton *)sender
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55acadd6e0f55a7e410046b0"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"china.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToFacebook,UMShareToQzone,UMShareToQQ,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite,nil]
                                       delegate:self];
}
//自定义顶部View
- (void)setTopView
{
    self.topView = [[FPRankView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kImageH(60))];
    self.topView.backgroundColor = [UIColor lightGrayColor];
    self.topView.alpha = 0.5;
    [self.view addSubview:_topView];
}
//添加底部自定义View
- (void)addWEbDownView
{
    self.webDownView = [[FPWebDownView alloc]initWithFrame:CGRectMake(0, kScreenHeight - kImageH(50), kScreenWidth, kImageH(50))];
    [self.webDownView.releationButton addTarget:self action:@selector(releationButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.webDownView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_webDownView];
}
//实现relationButton的点击方法
- (void)releationButtonAction:(UIButton *)sender
{
    [self creathideView];
    self.relationView.y = kScreenHeight - kImageH(200);
}
//添加底部隐藏View
- (void)creathideView
{
    self.relationView = [[FPRelationView alloc]initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kImageH(200))];
    self.relationView.backgroundColor = [UIColor lightGrayColor];
    self.relationView.collectionView.delegate = self;
    self.relationView.collectionView.dataSource = self;
    self.relationView.collectionView.contentSize = CGSizeMake(kScreenWidth * self.realations.count, 0);
    self.relationView.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self.relationView.canceButton addTarget:self action:@selector(canceButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_relationView];
}   
//实现取消按钮的方法
- (void)canceButtonAction:(UIButton *)sender
{
    
    self.relationView.y  =  kScreenHeight;
}
- (void)webAnalysisWithString:(NSString *)string
{
    NSURL *url = [NSURL URLWithString:string];
    //创建请求对象
  
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.0];
    //开启异步联接 用队列的形式进行一步请求数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil) return ;
        
        //请求的所有数据已经全部接受完成的时候 ,才会执行Block快里的方法 此时data就是我们请求下来的数据它会自动传回到这个参数上面
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        FPWebViewModel *model = [FPWebViewModel fpWebViewModelWithDictionary:dic];
        model.content = dic[@"content"];
        NSString *str = model.content;
        self.topView.titleName.text = model.title;
        self.topView.introLable.text = model.time;
        self.webDownView.messagelabel.text = [NSString stringWithFormat:@"%ld",model.commentCount];
        [self.webView loadHTMLString:str baseURL:nil];
        NSArray *arr = dic[@"relations"];
        for (NSDictionary *smallDic in arr) {
            FPWebRealationModel *RLModel = [FPWebRealationModel fpWebRealationModelwith:smallDic];
            [self.realations addObject:RLModel];
        
        }
    }];
}
#pragma mark ========实现collection的代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.realations.count == 0)return 0;
    return self.realations.count;
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"_item";
    [collectionView registerClass:[FPRelationItem class] forCellWithReuseIdentifier:cellIndentifier];
    FPRelationItem *item = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier forIndexPath:indexPath];
    FPWebRealationModel *model = self.realations[indexPath.row];
    [item.picImage sd_setImageWithURL:[NSURL URLWithString:model.image]placeholderImage:nil];
    item.nameLabel.text =model.name;
    if (model.year) {
    item.yearLabel.text = [NSString stringWithFormat:@"(%@)",model.year];
    }
   else
   {
       
   }
     
    return item;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kImageW(80), kImageH(120));
}
//据边缘的宽度
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(-30, 0, 10, 10);
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '90%'";
    [webView stringByEvaluatingJavaScriptFromString:str];
 


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.tabBarController.tabBar setHidden:NO];
}
@end
